﻿using System.Collections;
using System.Collections.Generic;
using System;
using Newtonsoft.Json;

public class BPInstructionSet
{
	protected bool abort = false;
	protected BPTrigger AttachTrigger { get; set; }

	public List<BPInstruction> LstInstruction { get; set; } = new List<BPInstruction>();

	[JsonIgnore]
	public int CurrentIndex { get; set; }
	[JsonIgnore]
	public bool IsAbort => abort;
	[JsonIgnore]
	public bool Abort { set => abort = value; }
	[JsonIgnore]
	public bool IsEnd
	{
		get
		{
			//空指令集标记为结束
			if (null == LstInstruction || LstInstruction.Count == 0)
				return true;
			//最后一个指令是否结束
			return LstInstruction[LstInstruction.Count - 1].IsEnded;
		}
	}

	public BPInstructionSet()
	{
		//TODO  Get A Param From BattleLevelEntity TO Create BPInstruction
		// Create All Instruction 
		LstInstruction = new List<BPInstruction>();

	}

	virtual public void DoStart(BPTrigger trigger)
	{
		this.AttachTrigger = trigger;
		for (int index = 0; index < LstInstruction.Count; index++)
		{
			LstInstruction[index].Reset(index);
		}
		_StartInstruction(0);
	}

	virtual public void DoUpdate(float deltaTime)
	{
		if (IsEnd)
			return;
		BPInstruction cur = _GetInstructionByIndex(CurrentIndex);
		if (null != cur)
			cur.DoUpdate(deltaTime);
		//TODO
		while (true)
		{

			if (null == cur)
			{
				cur = _StartInstruction(CurrentIndex + 1);
				if (null == cur)
					break;
			}

			if (IsAbort)
				break;
			if (!cur.IsEnded)
				break;

			cur = _StartInstruction(CurrentIndex + 1);
			if (null == cur)
				break;
			cur.DoUpdate(0);
		}
	}

	public BPInstruction GetInstructionByIndex(int index)
	{
		return _GetInstructionByIndex(index);
	}


	virtual protected BPInstruction _StartInstruction(int start)
	{
		CurrentIndex = start;
		BPInstruction instruction = _GetInstructionByIndex(start);
		if (null != instruction)
		{
			instruction.DoStart(this);
		}
		return instruction;
	}

	/// <summary>
	/// 返回第index个指令
	/// </summary>
	/// <param name="index"></param>
	/// <returns></returns>
	virtual protected BPInstruction _GetInstructionByIndex(int index)
	{
		if (null == LstInstruction || LstInstruction.Count == 0 || index >= LstInstruction.Count)
			return null;
		return LstInstruction[index];
	}

}
